/************************************************************************
 * The code is owned by mainframer.cn and Shang Tao
 * Without aproval of mainframer.cn and Shang Tao, removing the copyright
 * infomation is regarded as invassion of proprietary copyright
 ***********************************************************************/
package com.mr.qa.util.mail;

import java.io.File;
import java.io.UnsupportedEncodingException;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.Date;
import java.util.Properties;

import javax.activation.DataHandler;
import javax.activation.FileDataSource;
import javax.mail.MessagingException;
import javax.mail.SendFailedException;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.AddressException;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeBodyPart;
import javax.mail.internet.MimeMessage;
import javax.mail.internet.MimeMultipart;
import javax.mail.internet.MimeUtility;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import com.mr.qa.exception.QaException;

public class MailUtil
{
    static String smtpHost = "smtp.idccenter.net";//"mail.mainframer.cn";
    static String serviceFromMailBox = "service@mainframer.cn";
    static String serviceFromMailBoxPassword = "tsrqpo2009";
    private static final Log log = LogFactory.getLog(MailUtil.class);
    public MailUtil()
    {
    }
    //this method is used now
    public static void sendServiceSimpleHtmlMail(Mail simpleHtmlMail) throws QaException
    {
        Properties properties = System.getProperties();
        properties.put("mail.smtp.host", smtpHost);
        properties.put("mail.smtp.auth","true");
        /*
        Session session = Session.getDefaultInstance(properties,
                  new Authenticator() {
                      protected javax.mail.PasswordAuthentication getPasswordAuthentication() {
                          return new javax.mail.PasswordAuthentication
                          (serviceFromMailBox,serviceFromMailBoxPassword);
                      }
                  });
        */
        String password = simpleHtmlMail.getFromPassword();
        if(password == null)
            password = "tsrqpo2009";
        MailSmtpAuthenticator authenticator = new MailSmtpAuthenticator(simpleHtmlMail.getFrom(),password);
        Session session = Session.getDefaultInstance(properties,authenticator);
        //session.setDebug(true);
        MimeMultipart mailBody = new MimeMultipart();
        MimeBodyPart mimebodypart = new MimeBodyPart();
        try
        {
            //mimebodypart.setDataHandler(new DataHandler(simpleHtmlMail.getBody(), "text/html;charset=GBK"));
            //MimeUtility.encodeText(
            mimebodypart.setHeader("Content-Type","text/html;charset=GB2312");
            String body = simpleHtmlMail.getBody();
            //log.info("mail body="+body);
            mimebodypart.setContent(body,"text/html;charset=GB2312");
            mailBody.addBodyPart(mimebodypart);
            MimeMessage mimemessage = new MimeMessage(session);
            mimemessage.setFrom(new InternetAddress(simpleHtmlMail.getFrom()));
            //spport multiple recipients
            /*
            InternetAddress[] addresses = getRecipients(simpleHtmlMail.getTo());
            log.info("TO:"+addresses.length);
            mimemessage.setRecipients(javax.mail.Message.RecipientType.TO,addresses);
            */
            mimemessage.setRecipients(javax.mail.Message.RecipientType.TO,simpleHtmlMail.getTo());
            
            if(simpleHtmlMail.getCc() != null && simpleHtmlMail.getCc().length() > 0)
            {
                log.info("CC");
                mimemessage.setRecipients(javax.mail.Message.RecipientType.CC,simpleHtmlMail.getCc());
            }
            if(simpleHtmlMail.getBcc() != null && simpleHtmlMail.getBcc().length() > 0)
            {
                log.info("BCC");            
                mimemessage.setRecipients(javax.mail.Message.RecipientType.BCC,simpleHtmlMail.getBcc());
            }
            
            sun.misc.BASE64Encoder enc = new sun.misc.BASE64Encoder();
            String subject = simpleHtmlMail.getSubject();
            //log.info("mail subject="+subject);
            //mimemessage.setSubject("=?GB2312?B?"+enc.encode(subject.getBytes())+"?="); //not work for hotmail ok for yahoo
            //mimemessage.setSubject("=?GB2312?B?"+subject.getBytes()+"?="); //not ok for both
            //mimemessage.setSubject("=?GB2312?B?"+subject+"?=");//ok for both
            mimemessage.setSubject(subject);//ok for both
            mimemessage.setSentDate(new Date());
            if(simpleHtmlMail.getFilePath() != null && simpleHtmlMail.getFilePath().length() > 0)
                addFileAttachment(mailBody,simpleHtmlMail.getFilePath());
            else if(simpleHtmlMail.getUrl() != null && simpleHtmlMail.getUrl().length() > 0)
            {
                addUrlAttachment(mailBody,simpleHtmlMail.getUrl());
            }
            else if(simpleHtmlMail.getFormFile() != null)
            {
                addInputStreamAttachment(mailBody,new InputStreamDataSource(simpleHtmlMail.getFormFile()));
            }
            mimemessage.setContent(mailBody);
            Transport.send(mimemessage);
            log.info("send mail success");
        }
        catch(MessagingException me)
        {
            log.error("mail util MessagingException:"+me);
            if(me instanceof SendFailedException)
            {
                throw new QaException("mail-1",me);
            }
            else
                throw new QaException(me);
        }
        catch(UnsupportedEncodingException uee)
        {
            throw new QaException(uee);
        }
        catch(MalformedURLException mue)
        {
            throw new QaException(mue);
        }
        catch(Exception e)
        {
            log.error("mail util exception:"+e);
            throw new QaException(e);
        }
    }

    //no html mail with file attachment
    public static void sendServiceSimpleMailWithAttachment(Mail simpleMail) throws QaException
    {
        Properties properties = System.getProperties();
        properties.put("mail.smtp.host", smtpHost);
        properties.put("mail.smtp.auth","true");
        /*
        Session session = Session.getDefaultInstance(properties,
                  new Authenticator() {
                      protected javax.mail.PasswordAuthentication getPasswordAuthentication() {
                          return new javax.mail.PasswordAuthentication
                          (serviceFromMailBox,serviceFromMailBoxPassword);
                      }
                  });
                  */
        String password = simpleMail.getFromPassword();
        if(password == null)
            password = "tsrqpo2009";
        MailSmtpAuthenticator authenticator = new MailSmtpAuthenticator(simpleMail.getFrom(),password);
        Session session = Session.getDefaultInstance(properties,authenticator);
        try
        {
            MimeMessage mimemessage = new MimeMessage(session);
            mimemessage.setFrom(new InternetAddress(simpleMail.getFrom()));
            mimemessage.setRecipients(javax.mail.Message.RecipientType.TO,simpleMail.getTo());
            sun.misc.BASE64Encoder enc = new sun.misc.BASE64Encoder();  
            //mimemessage.setSubject(simpleMail.getSubject(),"GBK");
            mimemessage.setSubject("=?GB2312?B?"+enc.encode(simpleMail.getSubject().getBytes())+"?=");
    //          mimemessage.setText(simpleMail.getBody());
            mimemessage.setSentDate(new Date());
            MimeMultipart mailBody = new MimeMultipart();
            MimeBodyPart contentPart = new MimeBodyPart();
            contentPart.setText(simpleMail.getBody());
            mailBody.addBodyPart(contentPart);
            if(simpleMail.getFilePath() != null && simpleMail.getFilePath().length() > 0)
                 addFileAttachment(mailBody,simpleMail.getFilePath());
            else if(simpleMail.getFormFile() != null)
            {
                addInputStreamAttachment(mailBody,new InputStreamDataSource(simpleMail.getFormFile()));
            }
            mimemessage.setContent(mailBody);
            Transport.send(mimemessage);
        }
        catch(MessagingException me)
        {
            throw new QaException(me);
        }
        catch(UnsupportedEncodingException uee)
        {
            throw new QaException(uee);
        }
        catch(MalformedURLException mue)
        {
            throw new QaException(mue);
        }
        catch(Exception e)
        {
            System.out.println("mail util:"+e);
            throw new QaException(e);
        }
    }

    
    //no html mail without file attachment
    public static void sendServiceSimpleTextMail(Mail simpleMail) throws QaException
    {
        Properties properties = System.getProperties();
        properties.put("mail.smtp.host", smtpHost);
        properties.put("mail.smtp.auth","true");
        String password = simpleMail.getFromPassword();
        if(password == null)
            password = "tsrqpo2009";
        //MailSmtpAuthenticator authenticator = new MailSmtpAuthenticator(simpleMail.getFrom(),password);
        MailSmtpAuthenticator authenticator = new MailSmtpAuthenticator("service@mainframer.cn",password);
        Session session = Session.getDefaultInstance(properties,authenticator);
        session.setDebug(true);
        try
        {
            MimeMessage mimemessage = new MimeMessage(session);
            mimemessage.setFrom(new InternetAddress(simpleMail.getFrom()));
            //mimemessage.setDataHandler(new DataHandler(simpleMail.getBody(),"text/html;charset=gb2312"));
            mimemessage.setRecipients(javax.mail.Message.RecipientType.TO,simpleMail.getTo());
            mimemessage.setSubject(simpleMail.getSubject());
            mimemessage.setText(simpleMail.getBody());
            mimemessage.setSentDate(new Date());
            Transport.send(mimemessage);
        }
        catch(MessagingException me)
        {
            throw new QaException(me);
        }
    }


//the below methods are utilities

    //split the addresses delimitered with ";" to String[]
    static InternetAddress[] getRecipients(String mailAddresses) throws AddressException
{
        if(mailAddresses.indexOf(";") >= 0)
        {
            String[] _mailAddresses = mailAddresses.split(";");
            InternetAddress[] ia = new InternetAddress[_mailAddresses.length];
            log.info("address size:"+ia.length);
            for(int i=0;i<ia.length;i++)
            {
                log.info("i="+i+":"+_mailAddresses[i]);
                ia[i] = new InternetAddress(_mailAddresses[i]);
            }
            return ia;
        }
        else
        {
            InternetAddress[] ia = {new InternetAddress(mailAddresses)};
            log.info("i=0"+ia[0].getAddress());
            return ia;
        }
    }


    static void addInputStreamAttachment(MimeMultipart mimeBody,InputStreamDataSource inputStreamDataSource)throws
    MessagingException, MalformedURLException,UnsupportedEncodingException
{
        MimeBodyPart mimebodypart = new MimeBodyPart();
        mimebodypart.setDataHandler(new DataHandler(inputStreamDataSource));
        log.info("inputStreamDataSource name="+inputStreamDataSource.getName());
        mimebodypart.setFileName(MimeUtility. encodeText(inputStreamDataSource.getName()));
        mimeBody.addBodyPart(mimebodypart);
    }

    
    static void addUrlAttachment(MimeMultipart mimeBody,String urlAttachment)throws
    MessagingException, MalformedURLException 
    {
        MimeBodyPart mimebodypart = new MimeBodyPart();
        mimebodypart.setDataHandler(new DataHandler(new URL(urlAttachment)));
        mimeBody.addBodyPart(mimebodypart);
    }
    
    
    static void addFileAttachment(MimeMultipart mimeBody, String filePath) throws
    MessagingException, UnsupportedEncodingException 
    {
        File path = new File(filePath);
        if(!path.exists() || path.isDirectory())return;
        String strFileName = path.getName();
        MimeBodyPart mimebodypart = new MimeBodyPart();
        mimebodypart.setDataHandler(new DataHandler(new FileDataSource(filePath)));
        mimebodypart.setFileName(MimeUtility.encodeText(strFileName));
        // end of modify
        mimeBody.addBodyPart(mimebodypart);
    }
    
    public static void main(String[] args)
    {
        try
        {
            Mail htmlMail = new Mail();
            htmlMail.setFrom("resume01@mainframer.cn");
            //htmlMail.setTo("tao_shang@hotmail.com");
            htmlMail.setTo("tao_shang@hotmail.com");
            //htmlMail.setCc("ytstcn@yahoo.com.cn");
            //htmlMail.setBcc("forsimba@yahoo.com.cn");
            //htmlMail.setFormFile(file);
            //log.info("job title:"+jobTitle);
            htmlMail.setSubject("Apply for "+"xx"+" From www.mainframer.cn");
            htmlMail.setBody("<b>The resume</b> sent from www.mainframer.cn. Please don't reply");
            MailUtil.sendServiceSimpleTextMail(htmlMail);
            //sendServiceSimpleTextMail
        
            /*
            Mail htmlMail = new Mail();
            htmlMail.setFrom("service@mainframer.cn");
            htmlMail.setTo("tao_shang@hotmail.com");
            htmlMail.setCc("ytstcn@yahoo.com.cn");
            htmlMail.setBcc("forsimba@yahoo.com.cn");
            //htmlMail.setFilePath("D:\\MR\\admin.txt");
            htmlMail.setUrl("http://www.mainframer.cn/newsletter/");
            htmlMail.setSubject("resume");
            htmlMail.setBody("<b>resume</b><br><b>cv</b>");
            sendServiceSimpleHtmlMail(htmlMail);
            */
        }
        catch(Exception e)
        {
            System.out.println(e);
        }
    }
    
}
